package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.constant.IConstant;
import com.alvis.media.domain.UserEventLog;
import com.alvis.media.domain.other.KeyValue;
import com.alvis.media.domain.User;
import com.alvis.media.service.AuthenticationService;
import com.alvis.media.service.UserEventLogService;
import com.alvis.media.service.UserService;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.admin.user.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * CRUD方法的命名规则:
 * 增C  -- addXxx      createXxx              insertXxx
 * 查R  -- findXxx     queryXxx    getXxx     selectXxx
 * 改U  -- modifyXxx   changeXxx  alterXxx    updateXxx
 * 删D  -- removeXxx                          deleteXxx
 * <p>
 * 用户Controller层
 */
@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@AllArgsConstructor
public class UserController extends BaseApiController {


    /**
     * 用户业务层
     */
    private final UserService userService;

    private final UserEventLogService userEventLogService;

    private final AuthenticationService authenticationService;

    /**
     * 用户管理 -- 用户列表方法
     *
     * @param model 用户列表页面传来的数据
     * @return 响应给页面的JSON数据
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model) {
        // 1. 调用Service层查询用户列表的方法
        PageInfo<User> userPageInfo = userService.userPage(model);

        // 2. PageInfo<User>  -->  PageInfo<UserResponseVM>
        // PageInfo<UserResponseVM> userRespVMPageInfo = PageInfoHelper.copyMap(userPageInfo, user -> UserResponseVM.from(user));
        PageInfo<UserResponseVM> userRespVMPageInfo = PageInfoHelper.copyMap(userPageInfo, UserResponseVM::from);
        return RestResponse.ok(userRespVMPageInfo);
    }


    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> page = userEventLogService.page(model);

        PageInfo<UserEventLogVM> userEventLogVMPageInfo = new PageInfo(page.getList());

        return RestResponse.ok(userEventLogVMPageInfo);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> current() {
        User user = getCurrentUser();
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model) {
        User user = modelMapper.map(model, User.class);
        User userInfo = userService.getUserByUserName(model.getUserName());
        if (model.getId() == null) {
            //用户新增
            //根据用户名去DB中匹配，看该用户名是否可用？ --AJAX
            if (userInfo != null) {
                return new RestResponse<User>(IConstant.USER_ALREADY_EXSITS, "该用户名已存在,请修改!");
            }

            if (StringUtils.isBlank(model.getPassword())) {
                return new RestResponse<User>(IConstant.PWD_EMPTY, "请输入密码!");
            }

            String pwdEncode = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(pwdEncode);
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            user.setUserUuid(UUID.randomUUID().toString());
            userService.insertByFilter(user);
        } else {
            // 用户修改
            String pwdEncode = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(pwdEncode);
            user.setModifyTime(new Date());

            // 修改操作
            userService.updateByIdFilter(user);
        }
        return RestResponse.ok();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
        return RestResponse.ok();
    }

    /**
     * 用户管理 -- 用户列表查询页面中启用禁用功能
     *
     * @param id 要修改用户状态的用户ID
     * @return RestResponse<Integer>  页面要响应的数据
     */
    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        // 1.查询出要修改用户状态的用户信息
        User user = userService.getUserById(id);
        // 2. 调用用户Service层修改用户状态的方法
        Integer newStatus = userService.modifyUserStatus(user);
        user.setStatus(newStatus);
        user.setModifyTime(new Date());

        // 3. 做用户状态等的修改入库操作
        userService.updateByIdFilter(user);

        // 4. 将修改后的用户状态重新再传递给页面
        return RestResponse.ok(newStatus);
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        // 删除方案:
        // (1) 硬删除
        // userService.deleteById(id);

        // (2) 软删除
        User user = userService.getUserById(id);
        user.setDeleted(true);
        user.setModifyTime(new Date());

        // 入库
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }

    /**
     * 根据用户名模糊查询用户信息
     */
    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        // 根据用户名模糊查询用户信息
        List<KeyValue> keyValuesList = userService.selectUserByUserName(userName);
        return RestResponse.ok(keyValuesList);
    }


    @RequestMapping(value = "/getUserDetailByUserId/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> getUserDetailByUserId(@PathVariable Integer id) {

        return RestResponse.ok();
    }
}
